<template>
  <el-dialog v-model="props.visible" :footer="false" @close="emits('close')">
    <template #header="{ titleId, titleClass }">
      <div class="my-header flex">
        <h4 :id="titleId" :class="titleClass">
          <el-icon>
            <MemberAssignmentIcon />
          </el-icon>
          成员分配
        </h4>
        <div class="search-box">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索用户"
            class="search-input"
          />
          <el-button
            link
            @click="handleSearch"
            class="search-button"
            :icon="Search"
          >
          </el-button>
        </div>
      </div>
    </template>
    <div>
      <el-table
        ref="multipleTableRef"
        class="membertable"
        :data="tableData"
        style="width: 100%"
        table-layout="auto"
        height="50vh"
        :row-class-name="tableRowClassName"
        @scroll="handleScroll"
      >
        <el-table-column type="selection">
          <template #default="scope">
            <!-- {{ scope.row.isSelected }} -->
            <el-checkbox v-model="scope.row.isSelected" />
          </template>
        </el-table-column>
        <el-table-column label="姓名">
          <template #default="scope">
            <div class="flex">
              <span
                style="flex-shrink: 0; margin-right: 10px"
                v-html="scope.row.nickName"
              ></span>

              <el-button
                v-if="scope.row?.isManager === '0'"
                type="primary"
                size="small"
                plain
                @click="setManager(scope.row, true)"
              >
                设置管理员
              </el-button>
              <el-button
                v-if="scope.row?.isManager === '1'"
                type="info"
                size="small"
                plain
                @click="setManager(scope.row, false)"
              >
                撤销管理员
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          property="phoneNumber"
          label="联系方式"
          align="center"
        />
        <el-table-column property="limits" label="当前文件夹的文档操作权限">
          <template #default="scope">
            <div class="checkboxGroup">
              <el-checkbox
                label="浏览"
                v-model="scope.row.isBrowse"
                true-value="1"
                false-value="0"
                @change="checkChange('isBrowse', scope.row)"
              />
              <el-checkbox
                label="新增"
                v-model="scope.row.isAdd"
                true-value="1"
                false-value="0"
                @change="checkChange('isAdd', scope.row)"
              />
              <el-checkbox
                label="修改"
                v-model="scope.row.isEdit"
                true-value="1"
                false-value="0"
                @change="checkChange('isEdit', scope.row)"
              />
              <el-checkbox
                label="删除"
                v-model="scope.row.isDelete"
                true-value="1"
                false-value="0"
                @change="checkChange('isDelete', scope.row)"
              />
            </div>
          </template>
        </el-table-column>
        <template #append>
          <div class="load-tip">
            <span v-if="tableLoading">加载中...</span>
            <span v-else-if="!hasMore && tableData.length > 0"
              >没有更多数据了</span
            >
          </div>
        </template>
      </el-table>
      <div class="flex paginationBox">
        <!-- <el-pagination background layout="prev, pager, next" :total="50" /> -->
        <el-button
          type="default"
          @click="submitMemberList"
          v-loading="confirmAssignLoading"
          >确定</el-button
        >
      </div>
    </div>
  </el-dialog>
  <el-dialog
    v-model="SubmitDialog"
    title=""
    width="400px"
    align-center
    @close="vSubmitDialogClose"
  >
    <div class="submitDialog">
      <p>是否将该成员配置应用于该文件夹及所有子文件夹、子文档？</p>
    </div>
    <template #footer>
      <div class="dialog_footer">
        <el-button
          :disabled="countdown !== 0"
          @click="submitMemberListAction(false)"
          >否{{ countdown ? `(${countdown})` : "" }}</el-button
        >
        <el-button
          type="primary"
          :disabled="countdown !== 0"
          @click="submitMemberListAction(true)"
          >是{{ countdown ? `(${countdown})` : "" }}</el-button
        >
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { Folder, Search } from "@element-plus/icons-vue";
import { debounce } from "lodash-es";
import MemberAssignmentIcon from "@/assets/customIcon/MemberAssignment.vue";
// import { getFolderDetail } from "@/api/folder";
import {
  getFolderMemberList as getFolderMemberListApi,
  editFolderMember,
} from "@/api/folder";
import { getDocumentMemberList } from "@/api/document";
import { getUserList } from "@/api/account";
import { ElMessage, ElMessageBox } from "element-plus";
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  row: {
    type: Object,
    default: () => {},
  },
  structure: {
    type: String,
    default: "",
  },
});
const emits = defineEmits(["close","update"]);
const tableData = ref([]);
const searchKeyword = ref("");
const handleSearch = () => {
  console.log("handleSearch");
};

// const folderMemberList = ref([]);
// const folderMemberTotal = ref(0);
// const userList = ref([]);
const userTotal = ref(0);
const pagination = reactive({
  pageSize: 10,
  pageNum: 1,
});
const confirmAssignLoading = ref(false);
const setManager = (row, flag) => {
  // 调接口，设置管理员

  // 再修改表格数据
  row.isManager = flag ? "1" : "0";
};
const returnName = () => {
  if (props.structure == "folder") {
    return `文件夹[<font color="#409eff">${props.row.folderName}</font>]`;
  } else if (props.structure == "file") {
    return `文件[<font color="#409eff">${props.row.fileName}</font>]`;
  }
};
const checkChange = (key, row) => {
  console.log(key, row);
  if (row[key] === "1" && row.isSelected == false) {
    ElMessageBox.confirm(
      `该用户不是${returnName()}的成员，是否要添加该用户？`,
      "",
      {
        confirmButtonText: "是",
        cancelButtonText: "否",
        dangerouslyUseHTMLString: true,
      }
    )
      .then((res) => {
        row.isSelected = true;
      })
      .catch(() => {
        row[key] = "0";
      });
  }
};
let submitData = ref({
  edFolderMemberBoList: [],
  isCover: false,
});
const submitMemberList = () => {
  console.log(tableData.value, "tableData.value");
  // 处理要提交的数据
  if (props.structure == "folder") {
    tableData.value.forEach((item) => {
      if (item.isSelected) {
        submitData.value.edFolderMemberBoList.push({
          folderId: props.row.id,
          userName: item.userName,
          isBrowse: item.isBrowse,
          isAdd: item.isAdd,
          isEdit: item.isEdit,
          isDelete: item.isDelete,
        });
      }
    });
  }
  SubmitDialog.value = true;
  // submitProjectConfigForm() 改为单独弹窗控制
  countdownInterval.value = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--; // 减少倒计时
    } else {
      clearInterval(countdownInterval.value); // 清除倒计时
    }
  }, 1000); // 每秒更新一次
  // ElMessageBox.confirm("是否覆盖内部权限？", "", {
  //   distinguishCancelAndClose: true, //区分取消和关闭
  //   confirmButtonText: "是（3s）",
  //   cancelButtonText: "否（3s）",
  //   draggable: true,
  //   beforeClose: (action, instance, done) => {
  //     if (action === "confirm") {
  //       // 开始倒计时
  //       timer = setTimeout(() => {
  //         // 假设这里有一个异步操作，比如API请求
  //         this.handleConfirm();
  //         // 清除定时器
  //         clearTimeout(timer);
  //         // 关闭对话框
  //         done();
  //       }, 3000); // 3秒倒计时

  //       // 将确认按钮设置为加载状态
  //       instance.$el
  //         .querySelector(".el-button--confirm")
  //         .classList.add("is-loading");
  //       instance.$el.querySelector(".el-button--confirm span").innerText = "是"; // 清除按钮文本

  //       // 阻止对话框立即关闭
  //       return false;
  //     } else {
  //       done();
  //     }
  //   },
  // })
  //   .then(() => {
  //     // 覆盖
  //     submitData.value.isCover = true;
  //     submitMemberListAction();
  //   })
  //   .catch((action) => {
  //     if (action === "cancel") {
  //       // 不覆盖
  //       submitData.value.isCover = false;
  //       submitMemberListAction();
  //     } else {
  //       // 关闭弹窗，不提交
  //       ElMessage.info("关闭弹窗，取消操作");
  //     }
  //   });
};
const SubmitDialog = ref(false);
const countdown = ref(3); // 倒计时时间
const countdownInterval = ref(null);
// let timer = null;
const vSubmitDialogClose = () => {
  SubmitDialog.value = false;
  countdown.value = 3;
  clearInterval(countdownInterval.value);
  countdownInterval.value = null;
};

const submitMemberListAction = (flag) => {
  // ElMessage.info("正在提交...");
  confirmAssignLoading.value = true;
  submitData.value.isCover = flag;
  const data = { ...submitData.value };
  if (props.structure == "folder") {
    // editFolderMember(data)
    editFolderMember(data)
      .then((res) => {
        if (res.code == 200) {
          ElMessage.success("修改文件夹成员权限成功");
          emits('update')
        } else {
          ElMessage.error("修改文件夹成员权限失败");
        }
      })
      .catch((err) => {
        console.log(err);
        ElMessage.error("修改文件夹成员权限失败");
      })
      .finally(() => {
        confirmAssignLoading.value = false;
        vSubmitDialogClose();
      });
  }
};
const tableRowClassName = ({ row, rowIndex }) => {
  if (row.delFlag === "2") {
    return "disabled-row";
  }
  return "";
};
const hasMore = ref(true);
const tableLoading = ref(false);
// 滚动事件处理（带防抖）
const handleScroll = debounce((e) => {
  console.log("滚动事件触发", e);
  // 距离底部 300px 时触发
  const bottomThreshold = 300;
  const container = document.querySelector(".membertable .el-scrollbar");
  const parent = document.querySelector(".membertable tbody");
  console.log(container, parent);
  const conRect = container.getBoundingClientRect();
  const parentRect = parent.getBoundingClientRect();
  console.log(conRect, parentRect);
  if (parentRect.bottom - conRect.bottom <= bottomThreshold) {
    console.log("到底了");
    loadMore();
  }
}, 100);
const loadMore = () => {
  if (!hasMore.value || tableLoading.value) return;
  // 获取下一页列表数据
  getFolderMemberList();
};
// 处理数据
const transData = (data) => {
  return data.map((item) => ({ ...item, isSelected: item.id ? true : false }));
};
// 获取数据
const getFolderMemberList = async () => {
  if (!hasMore.value) return;
  tableLoading.value = true;
  return new Promise((resolve, reject) => {
    getFolderMemberListApi({
      folderId: props.row.id,
      ...pagination,
    })
      .then((res) => {
        if (res.code == 200) {
          if (pagination.pageNum == 1) {
            tableData.value = transData(res.rows);
          } else {
            tableData.value = [...tableData.value, ...transData(res.rows)];
          }
          userTotal.value = res.total;
          hasMore.value = userTotal.value > tableData.value.length;
          pagination.pageNum++;
          resolve(res);
        } else {
          reject(res);
        }
      })
      .catch((err) => {
        reject(err);
      })
      .finally(() => {
        tableLoading.value = false;
      });
  });
};
const getFileMemberList = async () => {
  if (!hasMore.value) return;
  return new Promise((resolve, reject) => {
    getDocumentMemberList({
      documentId: props.row.id,
      ...pagination,
    })
      .then((res) => {
        if (res.code == 200) {
          if (pagination.pageNum == 1) {
            tableData.value = transData(res.rows);
          } else {
            tableData.value = [...tableData.value, ...transData(res.rows)];
          }
          userTotal.value = res.total;
          hasMore.value = res.total > tableData.value.length;
          pagination.pageNum++;
          resolve(res);
        } else {
          reject(res);
        }
      })
      .catch((err) => {
        reject(err);
      });
  });
};
// const combineData = () => {
//   // 合并数据
//   tableData.value = userList.value.map((item) => {
//     const folderMember = folderMemberList.value.find(
//       (folderItem) => folderItem.userName == item.userName
//     );
//     console.log(folderMember, "folderMember");
//     if (folderMember) {
//       return { ...folderMember, isSelected: true };
//     } else {
//       return {
//         userName: item.userName,
//         nickName: item.nickName,
//         phoneNumber: item.phonenumber,
//         isBrowse: 1,
//         isAdd: 1,
//         isEdit: 1,
//         isDelete: 1,
//         isManager: 1,
//         isTop: 1,
//         isSelected: false,
//       };
//     }
//   });
// };
// 初始获取
// const initData = () => {
//   Promise.all([
//     getFolderMemberList({
//       folderId: props.row.id,
//       pageSize: 10,
//       pageNum: 1,
//     }),
//     getUserList({ pageSize: 10, pageNum: 1 }),
//   ])
//     .then((res) => {
//       console.log(res, "res");
//       if (res[0].code == 200 && res[1].code == 200) {
//         folderMemberList.value = res[0].rows;
//         userList.value = res[1].rows;
//         combineData();
//       } else {
//         ElMessage.error("系统错误");
//       }
//     })
//     .catch((err) => {
//       ElMessage.error("发生错误", err);
//     });
// };
onMounted(() => {
  // 获取需要的数据
  console.log(props.row, "props.row");
  if (props.structure == "folder") {
    getFolderMemberList();
  } else if (props.structure == "file") {
    getFileMemberList();
  }
});
</script>
<style lang="scss" scoped>
.el-dialog__title {
  display: flex;
  align-items: center;
  gap: 10px;
}
.my-header {
  justify-content: space-between;
  .search-box {
    display: flex;
    align-items: center;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    margin-right: 15px;
    .search-input {
      flex: 1;
      border-right: 1px solid #dcdfe6;
      :deep(.el-input__wrapper) {
        box-shadow: none;
      }
      .el-input__icon {
        cursor: pointer;
        font-size: 18px;
        &:hover {
          color: #409eff; /* Element Plus 主色调 */
        }
      }
    }
    .search-button {
      height: 100%;
      padding: 0 8px;
    }
  }
}
.checkboxGroup {
  :deep(.el-checkbox) {
    .el-checkbox__inner {
      background-color: #fff;
      border-color: var(--el-text-color-regular);
    }
  }
  :deep(.el-checkbox.is-checked) {
    color: red;
    .el-checkbox__input.is-checked {
      .el-checkbox__inner {
        &:after {
          border-color: var(--el-text-color-regular);
        }
      }
    }
    .el-checkbox__label {
      color: var(--el-text-color-regular);
    }
  }
}
.paginationBox {
  padding: 10px;
  justify-content: flex-end;
  gap: 20px;
}
</style>
<style>
.el-table .disabled-row {
  /* --el-table-tr-bg-color: var(--el-color-success-light-9); */
  color: #ccc;
}
</style>
